<?php

namespace app\admin\controller\flow;

use app\admin\model\AuthDepartment;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Session;
use workflow\workflow;
use think\Db;

/**
 * *工作流管理
 *
 * @icon fa fa-circle-o
 */
class Flow extends Backend
{
    
    /**
     * Flow模型对象
     * @var \app\admin\model\Flow
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Flow;
        $this->work = new workflow();
        $this->uid = session('admin.id');//获取用户id
        $this->role = session('admin.position');//职位信息
        $this->view->assign("typeList", $this->model->getTypeList());
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            var_dump($groups);
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($list as $key=>$item)
            {
                $list[$key]['edit'] = Db::name('run')->where('flow_id', $item['id'])->where('status', '0')->value('id');
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 设计流程
     * @return mixed
     */
    public function desc()
    {
        $flow_id = intval(input('flow_id'));
        if($flow_id<=0){
            $this->error('参数有误，请返回重试!');
        }
        $one = $this->work->FlowApi('GetFlowInfo',$flow_id);
        if(!$one){
            $this->error('未找到数据，请返回重试!');
        }
        $this->assign('one', $one);
        $this->assign('process_data',$this->work->ProcessApi('All',$flow_id));
        return $this->fetch();
    }

    /**
     * 新增步骤
     * @return \think\response\Json
     */
    public function add_process()
    {
        $flow_id = input('flow_id');
        $one = $this->work->FlowApi('GetFlowInfo',$flow_id);
        if(!$one){
            return json(['status'=>0,'msg'=>'添加失败,未找到流程','info'=>'']);
        }
        return json($this->work->ProcessApi('ProcessAdd',$flow_id));
    }

    /**
     * 保存布局
     * @return \think\response\Json
     */
    public function save_canvas()
    {
        return json($this->work->ProcessApi('ProcessLink',input('flow_id'),input('process_info')));
    }

    /**
     * 检查逻辑
     * @param $fid
     * @return mixed
     */
    public function Checkflow($fid)
    {
        return $this->work->SuperApi('CheckFlow',$fid);
    }

    /**
     * 删除步骤
     * @return \think\response\Json
     */
    public function del_allprocess()
    {
        return json($this->work->ProcessApi('ProcessDelAll',input('flow_id')));
    }

    /**
     * 步骤属性
     * @return mixed
     */
    public function wfatt()
    {
        $info = $this->work->ProcessApi('ProcessAttView',input('id'));
        $this->assign('op',$info['show']);
        $this->assign('one',$info['info']);
        $this->assign('from',$info['from']);
        $this->assign('process_to_list',$info['process_to_list']);
        $this->assign('child_flow_list',$info['child_flow_list']);
        return $this->fetch();
    }

    /**
     * 用户选择
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function super_user()
    {
        $this->assign('user',db('admin')->field('userid as id,username')->select());
        $this->assign('kid',input('kid'));
        return $this->fetch();
    }

    /**
     * 角色选择
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function super_role()
    {
        $this->assign('role',db('auth_group')->field('id,name as username')->select());
        return $this->fetch();
    }

    /**
     * 用户、角色搜索
     * @return array
     */
    public function super_get()
    {
        $type = trim(input('type'));
        if($type=='user'){
            $info =  db('admin')->where('username','like','%'.input('key').'%')->field('userid as value,username as text')->select();
        }else{
            $info =  db('base_position')->where('name','like','%'.input('key').'%')->field('id as value,name as text')->select();
        }
        return ['data'=>$info,'code'=>1,'msg'=>'查询成功！'];
    }

    /**
     * 保存步骤
     * @return \think\response\Json
     */
    public function save_attribute()
    {
        $data = input('post.');
        return json($this->work->ProcessApi('ProcessAttSave',$data['process_id'],$data));
    }

    /**
     * 流程监控
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wfjk()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('run')
                ->where('status','eq',0)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = Db::name('run')
                ->where('status','eq',0)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($list as $k=>$v)
            {
                $list[$k]['flow_name'] = Db::name('flow')->where('id','eq',$v['flow_id'])->value('flow_name');
                $process = Db::name('flow_process')->where('id','eq',$v['run_flow_process'])->find();
                if($process['auto_person'] == 4){
                    $list[$k]['user'] =$process['auto_sponsor_text'];
                }else{
                    $list[$k]['user'] =$process['auto_role_text'];
                }
                $tableComment = Db::query( "select table_comment from information_schema.tables where table_name =?",['hdyj_'.$v['from_table']]);
                $list[$k]['from_table_comment'] = $tableComment[0]['table_comment'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 选择,保存工作流
     * @return mixed
     */
    public function wfstart()
    {
        if($this->request->isAjax())
        {
            $data = $this->request->param();
            $flow = $this->work->startworkflow($data,$this->uid);
            if($flow['code']==1){
                return $this->success();
            }
            return $this->error($flow['msg']);
        }

        $info = ['wf_type'=>input('wf_type'),'wf_title'=>input('wf_title'),'wf_fid'=>input('ids')];
        $flow =  $this->work->getWorkFlow(input('wf_type'));
        $this->assign('flow',$flow);
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 终止任务
     */
    public function stop()
    {
        $flowinfo =  $this->work->SuperApi('WfEnd',input('ids'),$this->uid);
        if($flowinfo['code'] == -1)
        {
            $this->error();
        }
        return $this->success();
    }

    /**
     * 代审表单
     * @param $ids
     * @return mixed
     */
    public function run($ids)
    {
        $info = ['wf_title'=>input('wf_title'),'wf_fid'=>$ids,'wf_type'=>input('wf_type')];
        $this->assign('info',$info);
        $this->assign('flowinfo',$this->work->workflowInfo($ids,input('wf_type'),['uid'=>$this->uid,'role'=>$this->role]));
        return $this->fetch();
    }

    /**
     * 代审提交
     * @return mixed
     */
    public function do_check_save()
    {
        $data = $this->request->param();
        $flowinfo =  $this->work->workdoaction($data,$this->uid);
        $ret = ["code" => 0, "msg" => '操作成功!', "data" => []];
        $extend['opt'] = [
            'alert'    => '',
            'close'    => false,
            'redirect' => 'parent',
            'url'      => '',
        ];
        $ret = array_merge($ret, $extend);
        return json($ret);
    }

    /**
     * 退回提交
     * @return mixed
     */
    public function ajax_back(){
        $flowinfo =  $this->work->getprocessinfo(input('back_id'),input('run_id'));
        return $flowinfo;
    }

    /**
     * 上传附件
     * @return mixed
     */
    public function wfup()
    {
        return $this->fetch();
    }

    /**
     * 保存附件
     * @return \think\response\Json
     */
    public function wfupsave()
    {
        $files = $this->request->file('file');
        $insert = [];
        foreach ($files as $file) {
            $path = ROOT_PATH. '/public/uploads/';
            $info = $file->move($path);
            if ($info) {
                $data[] = $info->getSaveName();
            } else {
                $error[] = $file->getError();
            }
        }
        return $this->msg_return($data,0,$info->getInfo('name'));
    }

    public function msg_return($msg = "操作成功！", $code = 0,$data = [],$redirect = 'parent',$alert = '', $close = false, $url = '')
    {
        $ret = ["code" => $code, "msg" => $msg, "data" => $data];
        $extend['opt'] = [
            'alert'    => $alert,
            'close'    => $close,
            'redirect' => $redirect,
            'url'      => $url,
        ];
        $ret = array_merge($ret, $extend);
        return json($ret);
    }

    /**
     * 删除流程
     **/
    public function delete_process()
    {
        return json($this->work->ProcessApi('ProcessDel',input('flow_id'),input('process_id')));
    }

    public function view($table,$ids)
    {
        $row = Db::name($table)->where('id',$ids)->find();
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
        $this->view->assign("row", collection($row)->toArray());
        return $this->view->fetch();
    }
}
